<?php
use GatewayClient\Gateway;

class controller_rooms extends model_rooms{
    # 更新聊天室房间缓存并通知APP更新
    public function rooms_list_update_redis()
    {
        $sql = "SELECT * FROM `@@rooms` WHERE `state`=1 ORDER BY `sort` ASC";
        $data = $this->db->query($sql,3);
        # 单个聊天室的参数
        # '`id`,`name`,`explain`,`icon`,`roomtype`'
        $rooms = array();
        foreach ($data as $k=>$v)
        {
            $redis_key = $this->redisPrefix['CRLP'].$v['id'];
            $this->redisSet($redis_key, $v);
            $rooms[$k] = array(
                'id' => $v['id'],
                'name' => $v['name'],
                'explain' => $v['explain'],
                'icon' => $v['icon'],
                'roomtype' => $v['roomtype'],
            );
        }
        # 全部聊天室参数
        $this->redisSet($redis_key, $rooms);
        $pushArray = array(
            'state' => 200,
            'cmd' => 'updatecache',
        );
        Gateway::sendToGroup('public',json_encode($pushArray));
        $this->dialogue(array(
            'type' => 'success',
            'text' => "缓存更新成功",
            'auto' => true,
            'yes'  => array(
                'text' => '我知道了',
                'func' => '',
            ),
        ));
    }
    //列表-参数采集过滤
    //@param bool $get 提交方式$_GET或$_POST
    private  function  rooms_list_get_args($get=true){
        $para = $get ? $_GET : $_POST;
        $args = array();
        $args['sKey'] = $this->existsKeyInArray('sKey',$para,'S');
        $args['ps'] = $this->existsKeyInArray('ps',$para,'N',$this->pagesize);
        return $args;
    }
    //列表搜索-分页参数
    private function rooms_list_page_args($args){
        $page_args = array();
        if(!empty($args['sKey'])) $page_args['sKey'] = $args['sKey'];
        if(!empty($args['ps'])) $page_args['ps'] = $args['ps'];
        $page_args['page'] = '{page}';
        return $page_args;
    }
    //列表显示
    public function rooms_list(){
        $args = $this->rooms_list_get_args(true);
        $page_args = $this->rooms_list_page_args($args);
        $args['page_current'] = $this->get_page();

        $datas = $this->mod_rooms_list($args);
        $args['page_max'] = $this->get_maxpage($args['ps'],$datas['record']);

        $basepath = '/rooms/rooms_list';

        $this->display("rooms/rooms_list",array(
            'basepath' => $basepath,
            'datas' => $datas['datas'],
            'record' => $datas['record'],
            'page_max' => $args['page_max'],
            'page_current' => $args['page_current'],
            'page_url' => http_build_query($page_args),
            'extra' => '',
            'searchdata' => $args,
            'container' => '#iframe'
        ));
    }
    //更新状态
    public function rooms_list_state(){
        $id = $this->existsKeyInArray('id',$_GET,'N');
        $field = $this->existsKeyInArray('field',$_GET,'S');
        $page_args = array(
            'page' => $this->existsKeyInArray('page',$_GET,'N',1),
        );
        if(!$id || empty($field)) core::__403();
        $updateid = $this->update_state('@@rooms',$id,$field);
        if(!$updateid) core::error('状态更新失败');
        $this->addLog($this->authid,__FUNCTION__,$id,'');
        $this->dialogue(array(
            'type' => 'success',
            'text' => "状态更新成功",
            'auto' => true,
            'yes'  => array(
                'text' => '我知道了',
                'func' => 'JumpMainFrame("/rooms/rooms_list?'.http_build_query($page_args).'");',
            ),
        ));
        $this->pushUpdatecache();
    }
    //删除
    public function rooms_list_delete(){
        $id = $this->existsKeyInArray('id',$_GET,'N');
        $title = $this->existsKeyInArray('title',$_GET,'S');
        if(!$id) core::__403();
        $deleteid = $this->db->delete('@@rooms',array('id'=>$id));
        if(!$deleteid) core::error('删除操作失败');
        $this->addLog($this->authid,__FUNCTION__,$id,$title);
        $this->dialogue(array(
            'type' => 'success',
            'text' => '删除【'.$title."】操作成功",
            'auto' => true,
            'yes'  => array(
                'text' => '我知道了',
                'func' => 'JumpMainFrame("/rooms/rooms_list");',
            ),
        ));
        $this->pushUpdatecache();

    }
    private function rooms_list_add_edit_args($get = false){
        $para = $get ? $_GET : $_POST;
        unset($para["client_type"]);
        $args = array();
        $args['id'] = $this->existsKeyInArray('id',$para,'N');
        $args['name'] = $this->existsKeyInArray('name',$para,'S');
        $args['explain'] = $this->existsKeyInArray('explain',$para,'S');
        $args['icon'] = $this->existsKeyInArray('icon',$para,'S');
        $args['nosay'] = $this->existsKeyInArray('nosay',$para,'N');
        $args['roomtype'] = $this->existsKeyInArray('roomtype',$para,'N');
        $args['onlywhite'] = $this->existsKeyInArray('onlywhite',$para,'N');
        $args['state'] = $this->existsKeyInArray('state',$para,'N');
        $args['sort'] = $this->existsKeyInArray('sort',$para,'F');
        if(empty($para['name'])) core::error("名称不能为空");
        return $args;
    }
    //添加房间
    public function rooms_add(){
        $this->display("rooms/rooms_add",array(
            'basepath' => '/rooms/rooms_list',
            'container' => '#iframe',
            'maxsort' => $this->db->maxval('sort','@@rooms'),
        ));
    }
    //添加保存
    public function rooms_list_add_save(){
        $args = $this->rooms_list_add_edit_args(false);
        unset($args['id']);
        $_result = $this->db->insert('@@rooms',$args);
        if(!$_result) core::error("添加[".$args['title']."]失败".$_result);
        $this->addLog($this->authid,__FUNCTION__,$_result,$args['name']);
        $this->dialogue(array(
            'type' => 'success',
            'text' => "添加[".$args['name']."]成功",
            'auto' => true,
            'yes'  => array(
                'text' => '刷新',
                'func' => 'JumpMainFrame("/rooms/rooms_list");',
            ),
            'no'  => array(
                'text' => '返回',
            ),
        ));
        $this->pushUpdatecache();
    }
    //编辑
    public function rooms_list_edit(){
        $args['id'] = $this->existsKeyInArray('id',$_REQUEST,'N');
        $this->display("rooms/rooms_edit",array(
            'basepath' => '/rooms/rooms_list',
            'id' => $args['id'],
            'data' => $this->db->getRow('@@rooms','*',array('id'=>$args['id'])),
            'userLevel' => $this->mod_members_userLevel_forSelect(),
            'agentLevel' => $this->mod_members_agentLevel_forSelect(),
            'container' => '#iframe'
        ));
    }
    //编辑保存
    public function rooms_list_edit_save(){
        $args = $this->rooms_list_add_edit_args(false);
        $editid = intval($args['id']);
        unset($args['id']);
        $_result = $this->table_row_save('@@rooms',$args,array('id'=>$editid),true);
        if(!$_result) core::error("更新[".$args['name']."]失败");
        $this->addLog($this->authid,__FUNCTION__,$_result,$args['name']);
        $this->dialogue(array(
            'type' => 'success',
            'text' => "更新[".$args['name']."]成功",
            'auto' => true,
            'yes'  => array(
                'text' => '刷新',
                'func' => 'JumpMainFrame("/rooms/rooms_list");',
            ),
            'no'  => array(
                'text' => '返回',
            ),
        ));
        $this->pushUpdatecache();
    }
    # region 推送信息给聊天室
    public function rooms_list_push(){
        if($this->post){
            $para = $_POST;
            $roomid = $this->existsKeyInArray('roomid',$para,'N');
            $content = $this->existsKeyInArray('content', $para , 'S');
            if(empty($roomid)) core::error("房号错误");
            if(empty($content)) core::error('推送内容不能为空');

            $room_id = 'chat_'.$roomid;
            $result = array(
                'state' => 200,
                'cmd' => 'adminsay',
                'content' => $content,
            );
            $this->addLog($this->authid,__FUNCTION__,$roomid,$content);
            \GatewayClient\Gateway::sendToGroup($room_id, json_encode($result));
        }else {
            $basepath = '/rooms/rooms_list';
            $html = '<div id="mainbody">';
            $html .= '<div class="main">';
            $html .= '<div class="info">';
            $html .= '<form name="add_save" action="' . $basepath . '_push"  method="POST" target="ajax" func="form_submit">';
            $html .= '<input type="hidden" name="roomid" value="'.$_GET['id'].'" />';
            $html .= '<dl><dt>内容：</dt><dd><input type="text" name="content" class="int" value="" /></dd></dl>';
            $html .= '</form>';
            $html .= '</div>';
            $html .= '</div>';
            $html .= '</div>';
            $this->dialogue(array(
                'class' => '',
                'body' => $html,
                'yes' => array(
                    'text' => '推送',
                    'func' => '$("form[name=add_save]").submit();',
                ),
                'no' => array(
                    'text' => '关闭',
                ),
            ));
        }
    }
    //聊天室清屏
    public function rooms_clearcontent(){
        $para = $_REQUEST;
        $roomid = $this->existsKeyInArray('roomid',$para,'N');
        $room_id = 'chat_' . $roomid;
        if(empty($roomid)) core::error('房号错误');
        $result = array(
            'cmd' => 'clearcontent',
            'state' => 200,
        );
        \GatewayClient\Gateway::sendToGroup($room_id, json_encode($result));
        $this->addLog($this->authid,__FUNCTION__,$roomid,'通知清屏');
        $this->dialogue(array(
            'type' => 'success',
            'text' => "清屏成功",
            'auto' => true,
            'yes'  => array(
                'text' => '刷新',
                'func' => 'JumpMainFrame("/rooms/rooms_list");',
            ),
            'no'  => array(
                'text' => '返回',
            ),
        ));
    }
    //加入黑名单
    public function rooms_userlist_addblackuser()
    {
        $para = $_GET;
        if(substr($para['uno'],0,1)=='S')
        {
            core::error('游客无法加入黑名单');
        }
        $roomid = $para['roomid'];
        $args = array(
            'uno' => $para['uno'],
            'roomid' => $para['roomid'],
        );
        #加入到记录中
        $this->db->replace('@@rooms_blacklist', $args);
        # 重新设置Redis的值
        $redis_key = $this->redisPrefix['CRBL'].$roomid;
        $data = $this->db->query("SELECT `uno` FROM `rp_rooms_blacklist` WHERE `roomid`=" . $roomid,3);
        $this->redisSet($redis_key, $data);
        # 发送黑名单提示
        $data = array(
            'state' => 200,
            'cmd' => 'push',
            't' => 'ta',
            'msg' => '你已被【'.$para['roomname'].'】列入黑名单',//推送弹出文字
        );
        Gateway::sendToUid($para['uno'], json_encode($data));
        $this->dialogue(array(
            'type' => 'success',
            'text' => $para['uno']."已加到【".$para['roomname']."】的黑名单",
            'auto' => true,
            'yes'  => array(
                'text' => '刷新',
                'func' => 'JumpMainFrame("/rooms/rooms_userlist?roomid='.$para['roomid'].'");',
            ),
            'no'  => array(
                'text' => '返回',
            ),
        ));
    }
    //加入黑名单
    public function rooms_userlist_addwhiteuser()
    {
        $para = $_GET;
        if(substr($para['uno'],0,1)=='S')
        {
            core::error('游客无法加入白名单');
        }
        $roomid = $para['roomid'];
        $args = array(
            'uno' => $para['uno'],
            'roomid' => $para['roomid'],
        );
        #加入到记录中
        $this->db->replace('@@rooms_whitelist', $args);
        # 重新设置Redis的值
        $redis_key = $this->redisPrefix['CRWL'].$roomid;
        $data = $this->db->query("SELECT `uno` FROM `@@rooms_whitelist` WHERE `roomid`=" . $roomid,3);
        $this->redisSet($redis_key, $data);
        $this->dialogue(array(
            'type' => 'success',
            'text' => $para['uno']."已加到【".$para['roomname']."】的白名单",
            'auto' => true,
            'yes'  => array(
                'text' => '刷新',
                'func' => 'JumpMainFrame("/rooms/rooms_userlist?roomid='.$para['roomid'].'");',
            ),
            'no'  => array(
                'text' => '返回',
            ),
        ));
    }
    //把玩家踢出聊天室
    public function rooms_userlist_killuser(){
        //killuser
        $client_id = $this->existsKeyInArray('client_id', $_REQUEST, 'S');
        $roomid = $this->existsKeyInArray('roomid', $_REQUEST, 'N');
        if(empty($client_id)) core::error('客户端编号错误');
        $kill_user = \GatewayClient\Gateway::getSession($client_id);
        $result = array(
            'state' => 200,
            'cmd' => 'push',
            'msg' => '你被踢出了聊天室',
        );
        $this->addLog($this->authid,__FUNCTION__,$roomid,$kill_user['nickname']);
        \GatewayClient\Gateway::sendToClient($client_id, json_encode($result));
        \GatewayClient\Gateway::closeClient($client_id);
        $this->dialogue(array(
            'type' => 'success',
            'text' => $kill_user['nickname']."(".$kill_user['uno'].")已被踢出聊天室",
            'auto' => true,
            'yes'  => array(
                'text' => '刷新',
                'func' => 'JumpMainFrame("/rooms/rooms_userlist?roomid='.$roomid.'");',
            ),
            'no'  => array(
                'text' => '返回',
            ),
        ));
    }
    //聊天室用户管理
    public function rooms_userlist()
    {
        $para = $_REQUEST;
        $roomid = $this->existsKeyInArray('roomid',$para,'N');
        $room_id = 'chat_' . $roomid;
        if(empty($roomid)) core::error('房号错误');

        $this->display("rooms/rooms_userlist",array(
            'basepath' => '/rooms/rooms_userlist',
            'roomid' => $roomid,
            'roomdata' => $this->db->getRow('@@rooms','*',array('id'=>$roomid)),
            'userlist' => \GatewayClient\Gateway::getClientSessionsByGroup($room_id),
            'container' => '#iframe'
        ));
    }
    # endregion

    # region 聊天室黑/白名单管理
    //获取参数
    private function rooms_blacklist_get_args($get = true){
        $para = $get ? $_GET : $_POST;
        $args = array();
        $fromTime = date('Y-m-d',time());
        $args['sKey'] = $this->existsKeyInArray('sKey',$para,'S');
        $args['ps'] = $this->existsKeyInArray('ps',$para,'N',$this->pagesize);
        $args['roomid'] = $this->existsKeyInArray('liqtype',$para,'N');
        return $args;
    }
    //拼装页面参数
    private function rooms_blacklist_page_args($args)
    {
        $page_args = array();
        if(!empty($args['sKey'])) $page_args['sKey'] = $args['sKey'];
        if(!empty($args['ps'])) $page_args['ps'] = $args['ps'];
        if(!empty($args['roomid'])) $page_args['roomid'] = $args['roomid'];
        $page_args['page'] = '{page}';
        return $page_args;
    }

    public function rooms_blacklist()
    {
        $basepath = '/rooms/rooms_blacklist';

        $get = true;
        $args = $this->rooms_blacklist_get_args($get);
        $page_args = $this->rooms_blacklist_page_args($args);
        $args['page_current'] = $this->get_page();

        $datas = $this->mod_rooms_blacklist_list($args);
        $args['page_max'] = $this->get_maxpage($args['ps'],$datas['record']);


        $this->display("rooms/blacklist",array(
            'basepath' => $basepath,
            'datas' => $datas['datas'],
            'rooms' => $this->mod_rooms_forSelect(),
            'record' => $datas['record'],
            'page_max' => $args['page_max'],
            'thishref' => '/rooms/rooms_blacklist',
            'page_current' => $args['page_current'],
            'page_url' => http_build_query($page_args),
            'extra' => '',
            'searchdata' => $args,
            'container' => '#iframe'
        ));
    }
    //从黑名单中删除
    public function rooms_blacklist_delete()
    {
        $para = $_GET;
        $args = array(
            'uno' => $para['uno'],
            'roomid' => $para['roomid'],
        );
        #加入到记录中
        $this->db->replace('@@rooms_blacklist', $args);
        # 重新设置Redis的值
        $redis_key = $this->redisPrefix['CRBL'].$para['roomid'];
        $data = $this->db->query("DELETE FROM `@@rooms_blacklist` WHERE `roomid`=" . $para['roomid'] . " AND `uno`='".$para['uno']."' LIMIT 1",1);
        $this->redisSet($redis_key, $data);
        $this->dialogue(array(
            'type' => 'success',
            'text' => $para['uno']."已从【".$para['roomname']."】的黑名单中删除",
            'auto' => true,
            'yes'  => array(
                'text' => '刷新',
                'func' => 'JumpMainFrame("/rooms/rooms_blacklist?roomid='.$para['roomid'].'");',
            ),
            'no'  => array(
                'text' => '返回',
            ),
        ));
    }
    //获取参数
    private function rooms_whitelist_get_args($get = true){
        $para = $get ? $_GET : $_POST;
        $args = array();
        $fromTime = date('Y-m-d',time());
        $args['sKey'] = $this->existsKeyInArray('sKey',$para,'S');
        $args['ps'] = $this->existsKeyInArray('ps',$para,'N',$this->pagesize);
        $args['roomid'] = $this->existsKeyInArray('liqtype',$para,'N');
        return $args;
    }
    //拼装页面参数
    private function rooms_whitelist_page_args($args)
    {
        $page_args = array();
        if(!empty($args['sKey'])) $page_args['sKey'] = $args['sKey'];
        if(!empty($args['ps'])) $page_args['ps'] = $args['ps'];
        if(!empty($args['roomid'])) $page_args['roomid'] = $args['roomid'];
        $page_args['page'] = '{page}';
        return $page_args;
    }

    public function rooms_whitelist()
    {
        $basepath = '/rooms/rooms_blacklist';

        $get = true;
        $args = $this->rooms_whitelist_get_args($get);
        $page_args = $this->rooms_whitelist_page_args($args);
        $args['page_current'] = $this->get_page();

        $datas = $this->mod_rooms_whitelist_list($args);
        $args['page_max'] = $this->get_maxpage($args['ps'],$datas['record']);


        $this->display("rooms/whitelist",array(
            'basepath' => $basepath,
            'datas' => $datas['datas'],
            'rooms' => $this->mod_rooms_forSelect(),
            'record' => $datas['record'],
            'page_max' => $args['page_max'],
            'thishref' => '/rooms/rooms_whitelist',
            'page_current' => $args['page_current'],
            'page_url' => http_build_query($page_args),
            'extra' => '',
            'searchdata' => $args,
            'container' => '#iframe'
        ));
    }
    //从白名单中删除
    public function rooms_whitelist_delete()
    {
        $para = $_GET;
        $args = array(
            'uno' => $para['uno'],
            'roomid' => $para['roomid'],
        );
        #加入到记录中
        $this->db->replace('@@rooms_blacklist', $args);
        # 重新设置Redis的值
        $redis_key = $this->redisPrefix['CRWL'].$para['roomid'];
        $data = $this->db->query("DELETE FROM `@@rooms_whitelist` WHERE `roomid`=" . $para['roomid'] . " AND `uno`='".$para['uno']."' LIMIT 1",1);
        $this->redisSet($redis_key, $data);
        $this->dialogue(array(
            'type' => 'success',
            'text' => $para['uno']."已从【".$para['roomname']."】的白名单中删除",
            'auto' => true,
            'yes'  => array(
                'text' => '刷新',
                'func' => 'JumpMainFrame("/rooms/rooms_whitelist?roomid='.$para['roomid'].'");',
            ),
            'no'  => array(
                'text' => '返回',
            ),
        ));
    }
    # endregion


}